const router = require('express').Router();
const prisma = require('../db/client');
const middleware = require('@blocklet/sdk/lib/middlewares');
const {logger} = require('@blocklet/sdk/lib/config');
const user = middleware.user();
const {Configuration, OpenAIApi} = require("openai");
const env = require('../libs/env');

router.get('/list', user, async (req, res) => {
  const query = req.query
  await prisma.$connect();
  const send = await prisma.send.findMany({
    skip: query.pageNum * query.pageSize,
    take: query.pageSize * 1,
    orderBy: {
      id: 'asc',
    },
  })
  logger.debug(send)
  const recv = await prisma.receive.findMany({
    skip: query.pageNum * query.pageSize,
    take: query.pageSize * 1,
    orderBy: {
      id: 'asc',
    },
  })
  logger.debug(recv)
  await prisma.$disconnect()
  res.json({
    'send': send,
    'recv': recv
  })

})

router.post('/send', user, async (req, res) => {
  const body = req.body;
  logger.debug(body)
  await prisma.$connect();
  const send = await prisma.send.create({data: body})
  await prisma.$disconnect()
  res.json(send);
});

router.get('/recv/:id', user, async (req, res) => {
  const _id = req.params.id

  const send = await prisma.send.findFirst({
    where: {
      id: _id * 1,
    },
  })

  const recv = await prisma.receive.findFirst({
    orderBy: {
      id: 'desc',
    },
  })
  let _messages
  if (recv !== null && recv !== undefined && recv !== '') {
    _messages = [
      {"role": "system", "content": recv.content},
      {"role": send.did, "content": send.content},
    ]
  } else {
    _messages = [
      {"role": send.did, "content": send.content},
    ]
  }

  const configuration = new Configuration({
    apiKey: env.OPENAI_API_KEY,
  });

  logger.debug(_messages)

  const openai = new OpenAIApi(configuration);
  const response = await openai.createCompletion({
    model: "gpt-3.5-turbo",
    message: _messages,
    temperature: 0.7,
    max_tokens: 256,
    top_p: 1,
    frequency_penalty: 0.0,
    presence_penalty: 0.6,
  });
  logger.debug(response.data.choices)

  const result = {
    did: 'system',
    content: response.data.choices[0].content,
    r_time: new Date()
  }
  await prisma.receive.create({data: result})

  await prisma.$connect();
  res.json(response.data.choices[0])
})

module.exports = router;
